package com.online.onlineshop.services.impl;

import com.online.onlineshop.entity.Address;
import com.online.onlineshop.entity.OrderItem;
import com.online.onlineshop.entity.Orders;
import com.online.onlineshop.entity.Production;
import com.online.onlineshop.mapper.CartMapperVOMapper;
import com.online.onlineshop.mapper.OrderItemMapper;
import com.online.onlineshop.mapper.OrderMapper;
import com.online.onlineshop.mapper.ProductionMapper;
import com.online.onlineshop.services.ForAddressService;
import com.online.onlineshop.services.ForCartService;
import com.online.onlineshop.services.ForOrderService;
import com.online.onlineshop.vo.CartValueObject;
import com.online.onlineshop.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ForOrderServiceImpl implements ForOrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    ForAddressService forAddressService;
    @Autowired
    ForCartService forCartService;
    @Autowired
    ForCartService cartService;
    @Autowired
    CartMapperVOMapper cartMapperVOMapper;
    @Autowired
    ProductionMapper productionMapper;

    /**
     * @param aid      地址id
     * @param uid      用户id
     * @param userName 用户名
     * @param cids     商品Cids
     * @return
     */
    @Override
    @Transactional
    public Orders product(Integer aid, Integer uid, String userName, Integer[] cids) {
        Date date = new Date();

        List<CartValueObject> list = cartMapperVOMapper.findByCids(cids);
        long totalPrice = 0L;
        for (CartValueObject c : list) {
            totalPrice += c.getRealPrice() * c.getNum();
        }
        Address address = forAddressService.getByAid(aid, uid);
        Orders orders = new Orders();
        orders.setUid(uid);
        orders.setRecvName(address.getName());
        orders.setRecvPhone(address.getPhone());
        orders.setRecvProvince(address.getProvinceName());
        orders.setRecvCity(address.getCityName());
        orders.setRecvArea(address.getAreaName());
        orders.setRecvAddress(address.getAddress());
        orders.setStatus(0);
        orders.setTotalPrice(totalPrice);
        orders.setCreatedTime(new Date());
        orders.setCreatedUser(userName);
        Integer r = orderMapper.insertOrders(orders);
        if (r != 1) {
            throw new RuntimeException("生成订单异常");
        }
        for (CartValueObject cart : list) {
            // 创建订单商品数据
            OrderItem item = new OrderItem();
            // 补全数据：setOid(orders.getOid())
            item.setOid(orders.getOid());
            // 补全数据：pid, title, image, price, num
            item.setPid(cart.getPid());
            item.setTitle(cart.getTitle());
            item.setImage(cart.getImage());
            item.setPrice(cart.getRealPrice());
            item.setNum(cart.getNum());
            // 补全数据：4项日志
            item.setCreatedUser(userName);
            item.setCreatedTime(date);
            item.setModifiedUser(userName);
            item.setModifiedTime(date);
            //存货量减少 同步操作
            synchronized (this) {
                Production production = productionMapper.selectById(cart.getPid());
                int oldPriority = production.getPriority();
                production.setPriority(oldPriority + cart.getNum());
                int havingNum = production.getNum();
                int requiringNum = cart.getNum();
                int num = havingNum - requiringNum;
                if (num < 0) {
                    throw new RuntimeException("存货量不足，订单生成失败");
                } else {
                    production.setNum(num);
                    int rs = productionMapper.updateById(production);
                    if (rs != 1) {
                        throw new RuntimeException("插入订单商品数据时出现未知错误");
                    }
                }
            }
            // 插入订单商品数据
            Integer rows2 = orderItemMapper.insertOrderItems(item);
            if (rows2 != 1) {
                throw new RuntimeException("插入订单商品数据时出现未知错误");
            }
        }
        return orders;
    }

    @Override
    public List<OrderVO> selectOrderVO(Integer uid) {
        //查询封装订单信息VO
        return orderMapper.selectOrderVO(uid);

    }

    @Override
    public Orders selectById(int oid) {
        return orderMapper.selectById(oid);
    }


}
